package org.rain.core.sys.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.rain.common.util.bean.Beans;
import org.rain.common.util.Colls;
import org.rain.common.util.Strs;
import org.rain.core.model.PersistenceModel;
import org.rain.core.sys.mapper.SysDictMapper;
import org.rain.core.sys.model.entity.SysDict;
import org.rain.core.sys.model.req.SysDictItemReq;
import org.rain.core.sys.model.req.SysDictReq;
import org.rain.core.sys.model.resp.SysDictItemResp;
import org.rain.core.sys.model.resp.SysDictResp;
import org.rain.core.sys.service.ISysDictService;
import org.rain.core.util.Pages;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * created by yangtong on 2025/4/8 16:48:04
 * <br/>
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {
    @Override
    public IPage<SysDictResp> pageDict(SysDictReq dictReq) {
        IPage<SysDict> page = page(Pages.getPage(), Wrappers.<SysDict>lambdaQuery().eq(Strs.isNotEmpty(dictReq.getDictName()), SysDict::getDictName, dictReq.getDictName()).eq(SysDict::getType, 1));
        return Pages.transPage(page, item -> {
            SysDictResp resp = new SysDictResp();
            Beans.copyProperties(item, resp);
            return resp;
        });
    }

    @Override
    public void saveOrUpdateDict(SysDictReq dictReq) {
        SysDict dict = new SysDict();
        Beans.copyProperties(dictReq, dict);
        dict.setType(0);
        this.saveOrUpdate(dict);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDict(String id) {
        SysDict sysDict = getById(id);
        if (sysDict != null) {
            List<SysDict> list = list(Wrappers.<SysDict>lambdaQuery().eq(SysDict::getDictCode, sysDict.getDictCode()));
            if (Colls.isNotEmpty(list)) {
                List<String> ids = list.stream().map(PersistenceModel::getId).toList();
                removeBatchByIds(ids);
            }
        }

    }

    @Override
    public List<SysDictItemResp> listDictItem(SysDictItemReq dictItemReq) {
        List<SysDict> list = list( Wrappers.<SysDict>lambdaQuery().eq(SysDict::getDictCode, dictItemReq.getDictCode()).eq(SysDict::getType, 1));
        return list.stream().map(item -> {
            SysDictItemResp resp = new SysDictItemResp();
            Beans.copyProperties(item, resp);
            return resp;
        }).toList();

    }

    @Override
    public void saveOrUpdateDictItem(SysDictItemReq dictItemReq) {
        SysDict dict = new SysDict();
        Beans.copyProperties(dictItemReq, dict);
        dict.setType(1);
        this.saveOrUpdate(dict);
    }

    @Override
    public void deleteDictItem(String id) {
        removeById(id);
    }
}
